﻿using System;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Xml.Serialization;

namespace WhiteFlow.DevTrackingTool.UI.Models
{
    [Serializable]
    public class ExpenseReport : WorksheetItem
    {
        #region Constants

        /// <summary>
        /// The Expenses property name.
        /// </summary>
        public const string ExpensesPropertyName = "Expenses";

        /// <summary>
        /// The TotalExpense property name.
        /// </summary>
        public const string TotalExpensePropertyName = "TotalExpense";

        #endregion

        #region Fields

        private TrackingWorksheet owner;

        private ObservableCollection<Expense> expenses;

        private decimal totalExpense;

        #endregion

        #region Properties

        [XmlIgnore]
        public TrackingWorksheet Owner
        {
            get { return owner; }
        }

        [XmlArray(ElementName = ExpensesPropertyName, IsNullable = true)]
        [XmlArrayItem(ElementName = "Expense", IsNullable = false, Type = typeof(Expense))]
        public ObservableCollection<Expense> Expenses
        {
            get
            {
                if (expenses == null)
                    expenses = new ObservableCollection<Expense>();

                return expenses;
            }
            set
            {
                expenses = value;
                OnPropertyChanged("Expenses");

                OnWorksheetItemChanged();
            }
        }

        [XmlIgnore]
        public decimal TotalExpense
        {
            get { return totalExpense; }
            set
            {
                totalExpense = value;
                OnPropertyChanged(TotalExpensePropertyName);
            }
        }

        #endregion

        #region Constructors

        public ExpenseReport()
        {
            Expenses.CollectionChanged += new NotifyCollectionChangedEventHandler(OnExpensesCollectionChanged);
        }

        #endregion

        #region Event Handlers

        private void OnExpensesCollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            UpdateTotalExpense();
        }

        #endregion

        #region Public Methods

        public void SetOwner(TrackingWorksheet owner)
        {
            this.owner = owner;

            if (owner != null)
            {
                UpdateTotalExpense();
            }
        }

        public void UpdateTotalExpense()
        {
            decimal total = 0;

            foreach (Expense expense in Expenses)
            {
                total += expense.Amount;
            }

            TotalExpense = total;
        }

        #endregion
    }
}